package fr.sedoo.metadata.client.ui.widget.field.impl.keyword;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.view.client.DefaultSelectionEventManager;
import com.google.gwt.view.client.MultiSelectionModel;

import fr.sedoo.commons.client.widget.table.AbstractListTable;
import fr.sedoo.commons.shared.domain.AbstractDTO;
import fr.sedoo.commons.shared.domain.HasIdentifier;
import fr.sedoo.metadata.shared.domain.thesaurus.ThesaurusItem;

public class SingleLevelThesaurusSelectionTable extends AbstractListTable {

	MultiSelectionModel<HasIdentifier> selectionModel;

	public SingleLevelThesaurusSelectionTable() {
		super();
		hideToolBar();
		hideHeader();
	}

	@Override
	public void presenterDelete(HasIdentifier hasId) {
	}

	@Override
	public void presenterEdit(HasIdentifier hasId) {

	}

	@Override
	protected void initColumns() {
		selectionModel = new MultiSelectionModel<HasIdentifier>(AbstractDTO.KEY_PROVIDER);
		itemTable.setSelectionModel(selectionModel, DefaultSelectionEventManager.<HasIdentifier> createCheckboxManager());

		Column<HasIdentifier, Boolean> checkColumn = new Column<HasIdentifier, Boolean>(new PointedCheckboxCell(true, false)) {
			@Override
			public Boolean getValue(HasIdentifier object) {
				return selectionModel.isSelected(object);
			}
		};

		itemTable.addColumn(checkColumn);
		itemTable.setColumnWidth(checkColumn, 40, Unit.PX);

		ClickableTextColumn<HasIdentifier> nameColumn = new ClickableTextColumn<HasIdentifier>() {
			@Override
			public String getValue(HasIdentifier aux) {
				return ((ThesaurusItem) aux).getValue();
			}
		};

		nameColumn.setFieldUpdater(new FieldUpdater<HasIdentifier, String>() {

			@Override
			public void update(int index, HasIdentifier object, String value) {
				selectionModel.setSelected(object, true);

			}
		});
		itemTable.addColumn(nameColumn);
		itemTable.setColumnWidth(nameColumn, 10, Unit.PCT);

		hideHeader();
	};

	@Override
	public void addItem() {
	}

	@Override
	public String getAddItemText() {
		return "";
	}

	public void reset() {
		itemTable.setVisibleRangeAndClearData(itemTable.getVisibleRange(), true);
		init(new ArrayList<HasIdentifier>());
	}

	public void setThesaurusItems(List<ThesaurusItem> items, List<ThesaurusItem> selectedItems) {
		reset();
		init(items);
		for (ThesaurusItem item : selectedItems) {
			selectionModel.setSelected(item, true);
		}
	}

	public ArrayList<ThesaurusItem> getSelectedItems() {
		ArrayList<ThesaurusItem> result = new ArrayList<ThesaurusItem>();
		result.addAll((Collection<? extends ThesaurusItem>) selectionModel.getSelectedSet());
		return result;
	}

}
